from fastapi import APIRouter, HTTPException, Depends, Query
from typing import List, Optional
from sqlalchemy.orm import Session

from ..database import get_db
from ..models.question import Question
from ..schemas.question import QuestionResponse, AnswerCheck, AnswerResponse, RecordCreate
from ..crud.question import (
    get_questions_by_type,
    get_question_by_id,
    check_answer,
    save_question_record,
    get_wrong_questions
)

router = APIRouter(prefix="/questions", tags=["questions"])

@router.get("/exam/{subject}/{vehicle_type}", response_model=QuestionResponse)
async def get_exam_questions(
    subject: str,
    vehicle_type: str,
    exam_type: str = Query(..., description="考试类型：theory, special, sequence"),
    question_count: Optional[int] = Query(100, description="题目数量，默认100题"),
    db: Session = Depends(get_db)
):
    """
    获取考试题目
    :param subject: 科目类型 (k1, k4)
    :param vehicle_type: 车型 (A1, A2, B1, C1等)
    :param exam_type: 考试类型 (theory, special, sequence)
    :param question_count: 题目数量，默认100
    """
    try:
        questions = get_questions_by_type(
            db=db,
            subject=subject,
            vehicle_type=vehicle_type,
            exam_type=exam_type,
            limit=question_count
        )
        
        if not questions:
            raise HTTPException(
                status_code=404,
                detail=f"未找到符合条件的题目: {subject}/{vehicle_type}/{exam_type}"
            )
            
        return {
            "success": True,
            "data": questions,
            "total": len(questions)
        }
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

@router.get("/{question_id}", response_model=Question)
async def get_question_detail(
    question_id: int,
    db: Session = Depends(get_db)
):
    """获取题目详情"""
    question = get_question_by_id(db, question_id)
    if not question:
        raise HTTPException(
            status_code=404,
            detail=f"题目不存在: {question_id}"
        )
    return question

@router.post("/{question_id}/check", response_model=AnswerResponse)
async def check_question_answer(
    question_id: int,
    answer: AnswerCheck,
    db: Session = Depends(get_db)
):
    """检查答案"""
    try:
        result = check_answer(db, question_id, answer.user_answer)
        return result
    except ValueError as e:
        raise HTTPException(
            status_code=404,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

@router.post("/record")
async def save_record(
    record: RecordCreate,
    db: Session = Depends(get_db)
):
    """保存答题记录"""
    try:
        # 这里应该从token中获取user_id，暂时写死
        user_id = 1
        result = save_question_record(
            db=db,
            user_id=user_id,
            subject=record.subject,
            score=record.score,
            answers=record.answers
        )
        return {
            "success": True,
            "data": result
        }
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )

@router.get("/wrong")
async def get_user_wrong_questions(
    db: Session = Depends(get_db)
):
    """获取用户错题"""
    try:
        # 这里应该从token中获取user_id，暂时写死
        user_id = 1
        questions = get_wrong_questions(db, user_id)
        return {
            "success": True,
            "data": questions,
            "total": len(questions)
        }
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=str(e)
        ) 